<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="规格">
        <el-select v-model="queryParams.specId" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="item in specIdOption" :key="item.value" :label="item.label"
                     :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="制作日期">
        <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期"
                        style="width: 240px"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button style="margin-left: 20px" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
                   v-hasPermi="['archive:warehouseManagement:archiveBoxRecord:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" @click="handleUpdate"
                   v-hasPermi="['archive:warehouseManagement:archiveBoxRecord:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" @click="handleDelete"
                   v-hasPermi="['archive:warehouseManagement:archiveBoxRecord:delete']">删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="boxRecordList" :height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="id"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="规格" prop="specId" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="盒子数目" prop="boxNum" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="制作日期" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{dateFilter(scope.row.productiveTime)}}</span>
          </template>
      </el-table-column>
      <el-table-column label="创建人" prop="createUser" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" prop="createTime" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="备注" prop="notes" align="center" :show-overflow-tooltip="true"/>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加档案盒记录 -->
    <el-dialog :title="title" :visible.sync="open" width="35%" append-to-body>
      <el-form ref="boxForm" :model="boxForm" :rules="boxRules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格" prop="specId">
              <el-select v-model="boxForm.specId" placeholder="请选择规格" style="width: 100%;">
                <el-option v-for="item in specIdOption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="盒子数目" prop="boxNum">
              <el-input-number v-model="boxForm.boxNum" controls-position="right" placeholder="请输入盒子数目" :min="0"
                               style="width: 100%;"
                               onKeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="制作日期" prop="productiveTime">
              <el-date-picker v-model="boxForm.productiveTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
                              style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="notes">
              <el-input v-model="boxForm.notes" type="textarea" placeholder="请输入内容" ref="textareaRef"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="boxCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {formatTimeToStr} from '@/api/archive/warehouseManagement/date';
import estimateTableHeight from '@/mixins/estimateTableHeight'
import {
  boxspecList,
  getBoxRecord,
  addBoxRecord,
  getDetail,
  updateBoxRecord,
  deleteBoxRecord
} from "@/api/archive/warehouseManagement/archiveBoxRecord";

export default {
  name: "index",
  mixins: [estimateTableHeight], // 混入方法
  data() {
    const checkLength = (rule, value, callback) => {
      if (value) {
        var reg = /^(?!0)[0-9]{1,9}$/
        if (reg.test(value) === false) {
          callback(new Error('请输入数字，1-9位'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        specId: undefined
      },
      dateRange: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 档案盒记录表格数据
      boxRecordList: [],
      // 选中数组
      ids: [],
      specNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹出层表单
      boxForm: {},
      // 弹出层表单校验
      boxRules: {
        specId: [
          {required: true, message: "规格不能为空", trigger: "blur"}
        ],
        boxNum: [
          {required: true, message: "盒子数目不能为空", trigger: "blur"},
          {trigger: 'blur', validator: checkLength}
        ],
        productiveTime: [
          {required: true, message: "制作日期不能为空", trigger: "blur"}
        ]
      },
      // 规格下拉框
      specIdOption: []
    }
  },
  created() {
    this.getOption()
    this.getList();
  },
  methods: {
    getOption() {
      boxspecList().then(response => {
        this.specIdOption = response.rows.map(item => {
          var dw = ""
          if (item.specDw == 0) {
            dw = "mm"
          } else {
            dw = "cm"
          }
          return {
            value: item.specId,
            label: item.specName + dw
          }
        })
      })
    },
    dateFilter(date){
      return formatTimeToStr(date,'yyyy-MM-dd');
    },
    table_index(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log(this.dateRange)
      if (this.dateRange != null) {
        if (this.dateRange.length != 0) {
          this.queryParams.productiveTime = this.dateRange[0].toString()
          this.queryParams.edProductiveTime = this.dateRange[1].toString()
        }
      }
      this.getList();
      this.queryParams.productiveTime = ""
      this.queryParams.edProductiveTime = ""
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.specId = undefined
      this.dateRange = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 获取表格数据
    getList() {
      this.loading = true
      getBoxRecord(this.queryParams).then(response => {
        this.boxRecordList = response.rows;
        for (let i = 0; i < response.rows.length; i++) {
          // 渲染表格数据
          for (let j = 0; j < this.specIdOption.length; j++) {
            if (response.rows[i].specId == this.specIdOption[j].value) {
              this.boxRecordList[i].specId = this.specIdOption[j].label
            }
          }
        }
        this.total = response.total;
        this.loading = false
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection, "ewrwere");
      this.ids = selection.map(item => item.id)
      this.specNames = selection.map(item => item.specId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 重置表单
    reset() {
      this.boxForm = {
        specId: undefined,
        boxNum: undefined,
        productiveTime: undefined,
        notes: undefined
      }
      this.$nextTick(() => {
        this.$refs.textareaRef.$refs.textarea.style.height = 'auto'; // 重置高度
      });
    },
    // 新增
    handleAdd() {
      this.reset();
      this.title = "新增档案盒记录"
      this.open = true
      this.resetForm('boxForm')
    },
    // 修改
    handleUpdate(row) {
      if (this.single == false) {
        this.reset();
        this.resetForm('boxForm')
        const id = row.id || this.ids
        getDetail(id).then(resposne => {
          this.boxForm = resposne.data
          this.title = "修改档案盒记录"
          this.open = true
        })
      } else {
        this.$message({message: '请选择一条数据进行修改', type: 'warning'})
      }
    },
    // 删除按钮
    handleDelete(row) {
      const id = row.id || this.ids;
      const specName = row.specId || this.specNames;
      if (id.length <= 0) {
        this.$modal.msgWarning('请选择数据！')
        return false;
      }
      this.$modal.confirm('是否确认删除规格为"' + specName + '"的数据项？').then(function () {
        return deleteBoxRecord(id)
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {
      });
    },
    // 弹窗取消
    boxCancel() {
      this.open = false
    },
    submitForm: function () {
      this.$refs["boxForm"].validate(valid => {
        if (valid) {
          if (this.boxForm.id != undefined) {
            updateBoxRecord(this.boxForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            addBoxRecord(this.boxForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
</style>
